import asyncio  # noqa: F401
from dataclasses import asdict
from fastapi import status, HTTPException
from pydantic import BaseModel
from .config import app, dblock
from .error import ConflictError, InvalidError

class Course(BaseModel):
    cou_sn: int | None
    cou_no: str
    cou_name: str
    credit: float | None
    hours: int | None

@app.get("/api/course/list")
async def get_course_list() -> list[Course]:
    with dblock() as db:
        db.execute("""
        SELECT sn AS cou_sn, cou_no, cou_name, credit, hours
        FROM course
        ORDER BY cou_no, cou_name
        """)
        data = [Course(**asdict(row)) for row in db]
    return data

@app.post("/api/course", status_code=status.HTTP_201_CREATED)
async def new_course(course: Course) -> Course:
    with dblock() as db:
        db.execute(
            """
            INSERT INTO course (cou_no, cou_name, credit, hours)
            VALUES(%(cou_no)s, %(cou_name)s, %(credit)s, %(hours)s)
            RETURNING sn""",
            course.model_dump(),
        )
        row = db.fetchone()
        course.cou_sn = row.sn
    return course

@app.put("/api/course/{cou_sn}")
async def update_course(cou_sn: int, course: Course):
    assert course.cou_sn == cou_sn
    with dblock() as db:
        db.execute(
            """
            UPDATE course SET
                cou_no=%(cou_no)s, cou_name=%(cou_name)s, credit=%(credit)s, hours=%(hours)s
            WHERE sn=%(cou_sn)s;
            """,
            course.model_dump(),
        )

@app.delete("/api/course/{cou_sn}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_course(cou_sn):
    with dblock() as db:
        db.execute("DELETE FROM course WHERE sn=%(cou_sn)s", {"cou_sn": cou_sn}) 